package Controller;

import Backend.GeneralDatabase;
import Utilites.Log.SimpleLogger;
import view.Interface.window.PublicFatherWindow;
import view.LoginRigister.LoginMainWindow;
import view.LoginRigister.RigisterWindow;
import view.MainWindow.AdminMainWindow;
import view.MainWindow.UserMainWindow;
//import view.LoginRigister.LoginMainWindow;

public class LoginController {
    String username;
    GeneralDatabase database;

    public final PublicFatherWindow loginWindowOpener;
    public final PublicFatherWindow registerWindowOpener;

    public final AdminController adminController;
    public final UserController userController;

    public LoginController(GeneralDatabase database)
    {
        this.database = database;
        this.loginWindowOpener = new LoginMainWindow(this);
        this.registerWindowOpener = new RigisterWindow(this);
        this.adminController = new AdminController(database,username);
        this.userController = new UserController(database,username);

    }
    public LoginController(String username)
    {
        this.database = null;
        this.username = username;
        this.loginWindowOpener = new LoginMainWindow(this);
        this.registerWindowOpener = new RigisterWindow(this);
        this.adminController = new AdminController(database,username);
        this.userController = new UserController(database,username);
    }
    public String GetUsername() {
        return username;
    }
    public void tryLogin(String username, String password) {
        this.username = username;
        SimpleLogger.log("前端尝试登录用户"+username);
        String result = database.checker.tryLogin(username,password);

        if (result.equals("777")) {
            loginWindowOpener.dispose();
            SimpleLogger.log("切换到管理员主界面");
            adminController.start();
        } else if (result.equals("755")) {
            loginWindowOpener.dispose();
            SimpleLogger.log("切换到普通用户主界面");
            userController.start();
        } else{
            throw new RuntimeException("登陆失败，登录方法返回了非法值");
        }
    }
    public void start(){
        if(loginWindowOpener.Ready()){
            loginWindowOpener.open();
            SimpleLogger.log("GUI界面启动----登陆界面");
        }else{
            SimpleLogger.log("尝试启动UI界面，但界面暂未加载完毕");
        }
    }

    public void gotoRigister() {
        if(registerWindowOpener.Ready()){
            registerWindowOpener.open();
            SimpleLogger.log("打开注册界面");
        }else{
            SimpleLogger.log("尝试打开注册界面，但暂未加载完成");
        }
    }

    public void tryRigister(String username, String password) {
        database.checker.tryRigister(username,password);
        SimpleLogger.log("用户"+username+"注册成功");
    }

}
